/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.batavia.impl;

import com.batavia.domain.BantuLihatFlight;
import com.batavia.domain.Flight;
import com.batavia.inter.AirlineInterface;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.util.Cookie;
import java.io.IOException;
import java.util.ArrayList;

import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;

/**
 *
 * @author Saiful Bahri
 * blog    : http://bahrie27.wordpress.com/
 * twitter : @bahrie127
 */
public class ImplementFlight implements AirlineInterface {

    public List<Flight> search(Cookie cookie, Date departure, String origin, String destination, Integer adult, Integer infant) {
        try {

            WebClient client = new WebClient();
            client.setThrowExceptionOnScriptError(false);
            client.setCssEnabled(false);
            client.getCookieManager().addCookie(cookie);
            DateTime depart = new DateTime(departure);
            HtmlPage page = client.getPage("http://web.batavia-air.com/MyPage/index.php");

            HtmlForm form2 = page.getFormByName("searchbook");
            BantuLihatFlight blf = new BantuLihatFlight();
            blf.setStrTanggal(String.valueOf(depart.getDayOfMonth()));
            blf.setStrBulan(String.valueOf(depart.getMonthOfYear()));
            blf.setStrTahun(String.valueOf(depart.getYear()).substring(2, 4));
            blf.setJmlInfant(String.valueOf(infant));
            blf.setJmlPenumpang(String.valueOf(adult));
            blf.setRuteBerangkat(origin);
            blf.setRuteTujun(destination);
            
            form2.getSelectByName("ruteBerangkat").setSelectedAttribute(origin, true);
            form2.getSelectByName("ruteTujuan").setSelectedAttribute(destination, true);
           
            form2.getSelectByName("tglBerangkatPergi").setSelectedAttribute(String.valueOf(depart.getDayOfMonth()), true);
            form2.getSelectByName("blnBerangkatPergi").setSelectedAttribute(String.valueOf(depart.getMonthOfYear()), true);
            form2.getSelectByName("thnBerangkatPergi").setSelectedAttribute(String.valueOf(depart.getYear()).substring(2, 4), true);

            form2.getSelectByName("jmlPenumpang").setSelectedAttribute(adult.toString(), true);
            form2.getSelectByName("jmlInfant").setSelectedAttribute(infant.toString(), true);
            final HtmlSubmitInput bTN = form2.getInputByName("Submit");
            final HtmlPage page3 = bTN.click();


            List<HtmlElement> flatNo = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_FLTNO);
            List<HtmlElement> dep = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_DEP);
            List<HtmlElement> arr = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_ARR);
            List<HtmlElement> via = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_VIA);

            List<HtmlElement> z = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_Z);

            List<HtmlElement> w = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_W);
            List<HtmlElement> p = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_P);
            List<HtmlElement> n = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_N);
            List<HtmlElement> x = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_X);
            List<HtmlElement> r = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_R);
            List<HtmlElement> s = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_S);
            List<HtmlElement> t = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_T);
            List<HtmlElement> v = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_V);
            List<HtmlElement> q = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_Q);
            List<HtmlElement> b = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_B);
            List<HtmlElement> l = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_L);
            List<HtmlElement> m = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_N);
            List<HtmlElement> h = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_H);
            List<HtmlElement> d = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_D);
            List<HtmlElement> y = (List<HtmlElement>) page3.getByXPath(FlightConstans.XPATH_Y);

            List<Flight> result = new ArrayList<Flight>();

            for (int i = 1; i < flatNo.size(); i++) {

                Flight flg = new Flight();
                flg = parseFlight(departure, origin, destination, flatNo, dep, arr, via, i, z,
                        w, p, n, x, r, s,
                        t, v, q, b, l, m, h,
                        d, y);
                flg.setBfl(blf);
                if (flg.getFltNo().compareTo(" ") > 0) {
                    result.add(flg);

                }
            }


            client.closeAllWindows();
            return result;
        } catch (IOException ex) {

            java.util.logging.Logger.getLogger(ImplementFlight.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FailingHttpStatusCodeException ex) {

            java.util.logging.Logger.getLogger(ImplementFlight.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

    }

    public Flight parseFlight(Date departure, String origin, String destination, List<HtmlElement> fltNo, List<HtmlElement> dep, List<HtmlElement> arr, List<HtmlElement> via, int i,
            List<HtmlElement> z, List<HtmlElement> w, List<HtmlElement> p, List<HtmlElement> n, List<HtmlElement> x, List<HtmlElement> r, List<HtmlElement> s, List<HtmlElement> t, List<HtmlElement> v, List<HtmlElement> q, List<HtmlElement> b, List<HtmlElement> l, List<HtmlElement> m, List<HtmlElement> h, List<HtmlElement> d, List<HtmlElement> y) {

        Flight f = new Flight();
        f.setOrigin(origin);
        f.setDestination(destination);

        String kelas = parseClass(z.get(i).asText());
        f.setZ(kelas);
        kelas = parseClass(w.get(i).asText());
        f.setW(kelas);
        kelas = parseClass(p.get(i).asText());
        f.setP(kelas);
        kelas = parseClass(n.get(i).asText());
        f.setN(kelas);
        kelas = parseClass(x.get(i).asText());
        f.setX(kelas);
        kelas = parseClass(s.get(i).asText());
        f.setS(kelas);
        kelas = parseClass(r.get(i).asText());
        f.setR(kelas);
        kelas = parseClass(t.get(i).asText());
        f.setT(kelas);
        kelas = parseClass(v.get(i).asText());
        f.setV(kelas);
        kelas = parseClass(q.get(i).asText());
        f.setQ(kelas);
        kelas = parseClass(b.get(i).asText());
        f.setB(kelas);
        kelas = parseClass(l.get(i).asText());
        f.setL(kelas);
        kelas = parseClass(m.get(i).asText());
        f.setM(kelas);
        kelas = parseClass(h.get(i).asText());
        f.setH(kelas);
        kelas = parseClass(d.get(i).asText());
        f.setD(kelas);
        kelas = parseClass(y.get(i).asText());
        f.setY(kelas);

        f.setFltNo(fltNo.get(i).asText());
        f.setVia(via.get(i).asText());

        String[] rawOrigin = dep.get(i).asText().trim().split(" ");

        DateTime departureTime = parseTime(departure, rawOrigin);
        f.setDep(departureTime.toDate());

        String[] rawDes = arr.get(i).asText().trim().split(" ");
        DateTime ArrivalTime = parseTime(departure, rawDes);
        f.setArr(ArrivalTime.toDate());

        return f;
    }

    private String parseClass(String rowKelas) {
        String kelas = rowKelas.trim();

        kelas = StringUtils.remove(kelas, "None");
        kelas = StringUtils.remove(kelas, " ");
        kelas = StringUtils.remove(kelas, "unchecked");

        kelas = kelas.trim();


        return kelas;
    }

    private DateTime parseTime(Date departure, String[] rawString) {

        StringTokenizer dateHourMinute = new StringTokenizer(rawString[0], ".");
        String jam = dateHourMinute.nextToken();
        String menit = dateHourMinute.nextToken();

        DateTime departureTime = new DateTime(departure).withHourOfDay(Integer.valueOf(jam.trim())).withMinuteOfHour(Integer.valueOf(menit));

        return departureTime;
    }
}
